`
https://leetcode.cn/problems/shortest-and-lexicographically-smallest-beautiful-string/
`

/**
 * @param {string} s
 * @param {number} k
 * @return {string}
 */
var shortestBeautifulSubstring = function (s, k) {
  // 没有足够的 '1'
  if (s.split('').reduce((acc, cur) => acc + +cur, 0) < k) return ''

  const n = s.length
  // 窗口内 1 的数量
  let cnt = 0
  let res = s
  let left = 0, right = 0

  while (right < n) {
    const c = s[right++]
    cnt += +c

    // 1 太多或者左端点是 0 都要缩小，为了保持最短
    while (cnt > k || s[left] === '0') {
      const d = s[left++]
      cnt -= +d
    }

    if (cnt === k) {
      const target = s.substring(left, right)
      // 要么比 res 小，要么跟 res 长度相同，但字典序比 res 小
      if (target.length < res.length || target.length === res.length && target < res) {
        res = target
      }
    }
  }

  return res
};